package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WeChatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 老人家属Service业务层处理
 *
 * @author alexis
 * @date 2025-05-30
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Resource
    private WeChatService weChatService;
    @Resource
    private TokenService tokenService;

    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );


    /**
     * 小程序登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        // 获取openId
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());

        // 根据openId查询客户信息
        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FamilyMember::getOpenId, openId);
        FamilyMember familyMember = familyMemberMapper.selectOne(wrapper);

        // 如果客户信息不存在，则创建客户信息并且赋值openId
        if (ObjectUtil.isEmpty(familyMember)) {
            familyMember = FamilyMember.builder().openId(openId).build();
        }

        // 调用微信api获取用户绑定的手机号
        String phone = weChatService.getPhone(userLoginRequestDto.getPhoneCode());

        // 保存或修改用户
        saveOrUpdate(familyMember, phone);

        // 将用户id存入token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("nickName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }


    private void saveOrUpdate(FamilyMember familyMember, String phone) {
        // 判断取到的手机号与数据库中保存的手机号不一样
        if (ObjectUtil.notEqual(phone, familyMember.getPhone())) {
            familyMember.setPhone(phone);
        }

        // 判断id存在，则修改
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            familyMemberMapper.updateById(familyMember);
            return;
        }

        // id不存在，保存新用户
        // 随机组装昵称，词组+手机号后四位
        Random random= new Random();
        int index = random.nextInt(DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + phone.substring(phone.length()-4);
        familyMember.setName(nickName);
        familyMemberMapper.insert(familyMember);
    }
}
